package com.mmlc.meimei.lichengkongjian.mine;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.androidnetframe.httputil.BaseRequestFilterLayer;
import com.androidnetframe.responsejavabean.RequestError;
import com.androidnetframe.utils.LogUtils;
import com.mmlc.businessutils.OrderListUtils;
import com.mmlc.inter.InterActivity;
import com.mmlc.meimei.lichengkongjian.Adapter.OrderDetailAdapter;
import com.mmlc.meimei.lichengkongjian.App;
import com.mmlc.meimei.lichengkongjian.R;
import com.mmlc.meimei.lichengkongjian.been.ListItemBeanNew;
import com.mmlc.meimei.lichengkongjian.been.OrderButtonBean;
import com.mmlc.meimei.lichengkongjian.customview.ListViewForScrollView;
import com.mmlc.meimei.lichengkongjian.customview.MuchButtonGroup;
import com.mmlc.network.responsebean.OrderDetailResponseBean;
import com.mmlc.utils.PermissionUtils;
import com.mmlc.utils.ToastUtils;
import com.mmlc.utils.XUtils;

import org.xutils.image.ImageOptions;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

/**
 * Created by Administrator on 2016/8/11 0011.
 */
public class ActivityOrderDetail extends InterActivity implements ActivityCompat.OnRequestPermissionsResultCallback {

    @InjectView(R.id.tv_receivedName)
    TextView tvReceivedName;
    @InjectView(R.id.tv_phone)
    TextView tvPhone;
    @InjectView(R.id.tv_address)
    TextView tvAddress;
    @InjectView(R.id.lv_listView)
    ListViewForScrollView lvListView;
    @InjectView(R.id.tv_createTime)
    TextView tvCreateTime;
    @InjectView(R.id.tv_payTime)
    TextView tvPayTime;
    @InjectView(R.id.tv_sendTime)
    TextView tvSendTime;
    @InjectView(R.id.tv_commitTime)
    TextView tvCommitTime;
    @InjectView(R.id.mg_buttonGroup)
    MuchButtonGroup mgButtonGroup;
    @InjectView(R.id.rootView)
    public RelativeLayout rootView;
    @InjectView(R.id.tv_orderNumber)
    TextView tvOrderNumber;
    @InjectView(R.id.tv_orderState)
    TextView tvOrderState;
    @InjectView(R.id.tv_orderFrom)
    TextView tvOrderFrom;
    @InjectView(R.id.rl_orderFrom)
    RelativeLayout rlOrderFrom;
    @InjectView(R.id.tv_contact)
    TextView tvContact;
    @InjectView(R.id.tv_report)
    TextView tvReport;
    @InjectView(R.id.ll_pushInfo)
    LinearLayout llPushInfo;
    @InjectView(R.id.tv_pushreason)
    TextView tvReason;
    @InjectView(R.id.tv_pushname)
    TextView tvName;
    @InjectView(R.id.tv_pushstore)
    TextView tvPushStore;
    @InjectView(R.id.iv_pushhead)
    ImageView ivHead;
    @InjectView(R.id.iv_pushtype)
    ImageView ivType;
    @InjectView(R.id.iv_pushtp)
    ImageView ivTp;
    @InjectView(R.id.tv_title)
    TextView tvTitle;
    @InjectView(R.id.iv_back)
    ImageView ivBack;
    @InjectView(R.id.iv_set)
    ImageView iv_set;
    @InjectView(R.id.tv_order_price)
    TextView tv_order_price;
    @InjectView(R.id.tv_goods_price)
    TextView tv_goods_price;
    @InjectView(R.id.tv_freight_price)
    TextView tv_freight_price;
    @InjectView(R.id.tv_discount_price)
    TextView tv_discount_price;
    @InjectView(R.id.tv_coupon_price)
    TextView tv_coupon_price;
    @InjectView(R.id.tv_score_price)
    TextView tv_score_price;
    @InjectView(R.id.tv_integral)
    TextView tv_integral;

    @Override
    protected int initContentView() {
        return R.layout.activity_orderdetail;
    }

    @Override
    protected void initView() {
        ButterKnife.inject(this);
        processData();
    }

    public ListItemBeanNew adapterBean;
    public String phonenumber;

    private void processData() {
        Intent intent = getIntent();
        orderId = intent.getStringExtra("orderId");

        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finishUI(false);
            }
        });
        iv_set.setVisibility(View.GONE);
        tvTitle.setText("订单详情");
        //网络请求之后，就更新UI
        processUI();

    }

    @OnClick({R.id.tv_contact,R.id.tv_report})
    public void Onclick(View view){
        switch (view.getId()){
            case R.id.tv_contact:
                //6.0动态获取拨号权限
                PermissionUtils.requestPermission(this, PermissionUtils.CODE_CALL_PHONE, mPermissionGrant);
                break;
            case R.id.tv_report:
                Intent intent = new Intent(this, ActivityReport.class);
                intent.putExtra("order_id",orderId+"");
                startActivity(intent);
                break;
        }
    }



    private PermissionUtils.PermissionGrant mPermissionGrant = new PermissionUtils.PermissionGrant() {
        @Override
        public void onPermissionGranted(int requestCode) {
            switch (requestCode) {
                case PermissionUtils.CODE_CALL_PHONE:
                    try {
                        if(!TextUtils.isEmpty(phonenumber)) {
                            Intent it = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phonenumber));
                            it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(it);
                        }else{
                            ToastUtils.showToast("未获取到联系方式");
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    break;
                default:
                    PermissionUtils.requestPermission(ActivityOrderDetail.this, PermissionUtils.CODE_CALL_PHONE, mPermissionGrant);
                    break;
            }
        }
    };

    @Override
    public void onRequestPermissionsResult(final int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        PermissionUtils.requestPermissionsResult(this, requestCode, permissions, grantResults, mPermissionGrant);

    }

    public String orderId;
    OrderDetailFilter filter;

    public void processUI() {
        if (filter == null) {
            filter = new OrderDetailFilter(ActivityOrderDetail.this);
        }

        filter.requestBean.method = "orderDetail";
        filter.requestBean.order_id = orderId;
        filter.offerErrorParams(rootView);
        filter.sendRequest(new BaseRequestFilterLayer.AccessResultFromFilter<OrderDetailResponseBean>() {

            @Override
            public void onSuccess(OrderDetailResponseBean result) {
                if(result!=null) {
                    adapterBean = filter.responseBean;
                    adapterBean.type = result.getData().getType() + "";
                    if(!TextUtils.isEmpty(result.getData().getTip())){
                        adapterBean.tip = result.getData().getTip();

                    }
                    String type = result.getData().getType();
                    if (adapterBean.itemBeenList.size() > 0) {
                        processList(result);
                    } else {
                        filter.AddNoDataUI();
                    }
                    if (Integer.parseInt(type) > 0) {
                        phonenumber = result.getData().getPush_user_info().getPhone();
                        if (Integer.parseInt(type) == 1) {
                            ivType.setImageDrawable(ActivityOrderDetail.this.getResources().getDrawable(R.drawable.order_store));
                            ivTp.setImageDrawable(ActivityOrderDetail.this.getResources().getDrawable(R.drawable.order_store));
                            ivTp.setVisibility(View.VISIBLE);
                            llPushInfo.setVisibility(View.VISIBLE);
                        }
                        if (Integer.parseInt(type) == 2) {
                            ivType.setImageDrawable(ActivityOrderDetail.this.getResources().getDrawable(R.drawable.order_push));
                            ivTp.setImageDrawable(ActivityOrderDetail.this.getResources().getDrawable(R.drawable.order_push));
                            ivTp.setVisibility(View.VISIBLE);
                            llPushInfo.setVisibility(View.VISIBLE);

                        }
                        if(!TextUtils.isEmpty(result.getData().getPush_msg())) {
                            tvReason.setText(result.getData().getPush_msg());
                        }
                        if(!TextUtils.isEmpty(result.getData().getPush_user_info().getTname())) {
                            tvName.setText(result.getData().getPush_user_info().getTname());

                        }
                        if(!TextUtils.isEmpty(result.getData().getPush_user_info().getName())) {
                            tvPushStore.setText(result.getData().getPush_user_info().getName());
                        }
                        String headerurl = result.getData().getPush_user_info().getHeader_thumb();
                        if (!TextUtils.isEmpty(headerurl)) {
                            XUtils.image(ivHead,headerurl, new ImageOptions.Builder().setCircular(true).build());
                        }
                    }
                    if (Integer.parseInt(type) == 3) {
                        ivType.setImageDrawable(ActivityOrderDetail.this.getResources().getDrawable(R.drawable.ic_fast));
                        ivTp.setImageDrawable(ActivityOrderDetail.this.getResources().getDrawable(R.drawable.ic_fast));
                        ivTp.setVisibility(View.VISIBLE);


                    }

                    if( null != result.getData().getPush_user_info() && result.getData().getPush_user_info().getId()!=null
                            &&!TextUtils.isEmpty(App.user.getUserId())){
                        if(App.user.getUserId().equals(result.getData().getPush_user_info().getId())){
                            tvContact.setVisibility(View.GONE);
                            tvReport.setVisibility(View.GONE);
                        }else{
                            tvContact.setVisibility(View.VISIBLE);
                            tvReport.setVisibility(View.VISIBLE);
                        }
                    }
                    tv_integral.setText(result.getData().getGift_score());

                }else{
                    ToastUtils.showToast("解析数据错误");
                }

            }


            @Override
            public void onFailed(View errorLayout, RequestError serverError, int failedType) {
                ToastUtils.showToast(serverError.mess);
            }
        });

    }

    private void processList(OrderDetailResponseBean result) {
        //  OrderDetailBean detailOrderBean = ShopOrderUtils.getDetailOrderBean();
        initUI(result);

        OrderDetailAdapter adapter = new OrderDetailAdapter(adapterBean, ActivityOrderDetail.this);
        lvListView.setAdapter(adapter);
    }

    private void initUI(final OrderDetailResponseBean data) {

        final OrderDetailResponseBean.DataBean.OrdermailBean bean = data.getData().getOrdermail();
        if(null!= bean) {
            if(!TextUtils.isEmpty(bean.getBuyer_name())) {
                tvReceivedName.setText("收货人: " + bean.getBuyer_name());
            }
            if(!TextUtils.isEmpty(bean.getRegion_name())) {
                tvAddress.setText(bean.getRegion_name());
            }
            if(!TextUtils.isEmpty(bean.getBuyer_phone())) {
                tvPhone.setText(bean.getBuyer_phone());
            }
        }

        //商品id
        final String id = data.getData().getOrder_goods().get(0).getId();
        LogUtils.e("进入详情页的id",id);

        //订单号
        tvOrderNumber.setText("订单编号:" + data.getData().getId());

        //订单状态
        tvOrderState.setText(data.getData().getStatus_msg());
        //订单金额
        tv_order_price.setText("¥ "+data.getData().getOrder_price()+"");
        //商品总金额
        tv_goods_price.setText("¥ "+data.getData().getGoods_price()+"");
        //运费金额
        if(!TextUtils.isEmpty(data.getData().getFreight_price())){
            tv_freight_price.setText("+ ¥ "+data.getData().getFreight_price()+"");
        }
        //折扣金额
        if(!TextUtils.isEmpty(data.getData().getDiscount_price())){
            tv_discount_price.setText("-  ¥ "+data.getData().getDiscount_price()+"");
        }
        //优惠券
        if(!TextUtils.isEmpty(data.getData().getCoupon_price())){
            tv_coupon_price.setText("-  ¥ "+data.getData().getCoupon_price()+"");
        }
        //积分
        if(!TextUtils.isEmpty(data.getData().getScore_price())){
            tv_score_price.setText("-  ¥ "+data.getData().getScore_price()+"");
        }

        String add_time = data.getData().getAdd_time();
        if (TextUtils.isEmpty(add_time)) {
            tvCreateTime.setVisibility(View.GONE);
        } else {
            tvCreateTime.setVisibility(View.VISIBLE);
            tvCreateTime.setText("下单时间: " + add_time);
        }

        String pay_time = data.getData().getPay_time();
        if (TextUtils.isEmpty(pay_time)) {
            tvPayTime.setVisibility(View.GONE);
        } else {
            tvPayTime.setVisibility(View.VISIBLE);
            tvPayTime.setText("支付时间: " + pay_time);
        }

        String send_time = data.getData().getShip_time();
        if (TextUtils.isEmpty(send_time)) {
            tvSendTime.setVisibility(View.GONE);
        } else {
            tvSendTime.setVisibility(View.VISIBLE);
            tvSendTime.setText("发货时间: " + send_time);
        }


        String confirm_time = data.getData().getConfirm_time();
        if (TextUtils.isEmpty(confirm_time)) {
            tvCommitTime.setVisibility(View.GONE);
        } else {
            tvCommitTime.setVisibility(View.VISIBLE);
            tvCommitTime.setText("成交时间: " + confirm_time);
        }

        OrderDetailResponseBean.DataBean.OperBean oper = data.getData().getOper();
        //强制隐藏下方状态栏的申请售后按钮
        oper.setSale_after(0);
        mgButtonGroup.addButton(OrderListUtils.getOper(oper));
        mgButtonGroup.setMuchButtonClickedListener(new MuchButtonGroup.MuchButtonClickedListener() {
            @Override
            public void clicked(View v, int type) {
                OrderListUtils d = new OrderListUtils();
                d.doSomething(getOrderButtonBean(v, type));
                d.setUpdateUI(new OrderListUtils.UpdateUI() {
                    @Override
                    public void updateUI(int position, int type) {
                        switch (type) {
                            case OrderListUtils.UpdateUI.FINISH:
                                finishUI(true);
                                break;

                            case OrderListUtils.UpdateUI.REMOVE_ITEM:
                                break;
                        }
                    }
                });
            }

            private OrderButtonBean getOrderButtonBean(View v, int type) {

                OrderButtonBean buttonBean = new OrderButtonBean();
                buttonBean.rootView = rootView;
                buttonBean.activity = ActivityOrderDetail.this;
                buttonBean.itemPositon = -1;
                buttonBean.orderId = orderId;
                buttonBean.context = activity;
                buttonBean.isDetail = true;
//                buttonBean.goodsId = -1 + "";
                buttonBean.goodsId = data.getData().getOrder_goods().get(0).getId();
                buttonBean.tip = data.getData().getTip();
                buttonBean.buttonType = type;
                buttonBean.payType = adapterBean.payCode;
                buttonBean.buttonView = v;
//                buttonBean.detailSuborder = data.getData().getSuborder();
                buttonBean.orderType = Integer.parseInt(data.getData().getType());
                buttonBean.from = OrderButtonBean.ORDER_DETAIL;
                return buttonBean;
            }
        });
    }


    @Override
    protected void initEvent() {

    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getRepeatCount() == 0) {
            finishUI(false);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * true:刷新
     * false: 不刷新
     */
    public void finishUI(boolean isRefresh) {
        if (isRefresh) {//通知接收者，要刷新界面
            Intent intent = new Intent();
            intent.putExtra("state", 1);
            setResult(RESULT_OK, intent);
        }
        finish();
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.inject(this);
    }
}
